#!/usr/bin/env python
import os

def start_websockify(args):
    import subprocess, signal
    """
        启动 websockify
    """
    child = subprocess.Popen(args, cwd=os.path.dirname(os.environ.get("PWD")))
    def exit_signal(signal):
        child.send_signal(signal)
        os.sys.exit(0)
    signal.signal(signal.SIGINT, exit_signal)
    signal.signal(signal.SIGTERM, exit_signal)

if __name__ == '__main__':
    """
        正式启动不带参数
    """
    release = len(os.sys.argv) < 2
    # 带参数启动不运行 websockify 模块
    if not os.environ.get('RUN_MAIN') and release:
        start_websockify([
            "python",
            "-m",
            "websockify",
            '--token-plugin=BaseTokenAPI',
            '--token-source=http://localhost:8000/virt/display/info/?token=%s',
            '8009'
            ])
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    argv = ['manage.py', 'runserver', '127.0.0.1:8000'] if release else os.sys.argv
    execute_from_command_line(argv)